import { PrismaService } from './../common/prisma.service'
import { ConfigService } from './../common/config.service'
import { Injectable, UnauthorizedException } from '@nestjs/common'
import { PassportStrategy } from '@nestjs/passport'
import { ExtractJwt, Strategy } from 'passport-jwt'
import { User } from '@prisma/client'

/**
 * 需要在 auth.module.ts 中注入 JwtStrategy，以使用 JWT 令牌身份验证。
 * providers: [xxxx,JwtStrategy]
 */

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
	constructor(config: ConfigService, private prisma: PrismaService) {
		super({
			// 解析用户提交的 Bearer Token 数据
			jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
			// 加密的密钥 secret
			secretOrKey: config.get('JWT_SECRET') // Default:'secret'
		})
	}

	async validate({ id }): Promise<User> {
		const user = await this.prisma.user.findUnique({
			where: { id }
		})
		if (!user) throw new UnauthorizedException()
		return user
	}
}
